﻿#pragma execution_character_set("utf-8")
#ifndef CUSTOMTABLEWIDGET_H
#define CUSTOMTABLEWIDGET_H
#include <QTableWidget>
#include <QKeyEvent>
#include <QClipboard>
#include <QHeaderView>
#include <QDebug>
#include <QGuiApplication>

class CustomTableWidget : public QTableWidget
{
public:
    CustomTableWidget(QWidget *parent = nullptr) : QTableWidget(parent) {
//        this->horizontalHeader()->setStyleSheet("QHeaderView::section { border-bottom: 1px solid black; }");
    }

protected:
    void keyPressEvent(QKeyEvent *event) override
    {
        if (event->matches(QKeySequence::Copy)) {
            Copy();
        }

        QTableWidget::keyPressEvent(event);
    }

    //发现一个非常奇怪的问题，QTableWidgetItem *item中保存的是文字时，设置剪切板就会出问题，保存的是数字时，就没啥问题
    void Copy()
    {
        QTableWidgetSelectionRange range = this->selectedRanges().first(); // 获取第一个选定范围
        QString clipboardText;

        for (int row = range.topRow(); row <= range.bottomRow(); ++row) {
            for (int column = range.leftColumn(); column <= range.rightColumn(); ++column) {
                QTableWidgetItem *item = this->item(row, column);
                if (item) {
                    clipboardText += item->text() + "\t"; // 使用制表符分隔单元格
                }
            }
            clipboardText.chop(1); // 移除末尾的制表符
            clipboardText += "\n"; // 换行以分隔行
        }

        QClipboard *clipboard = QApplication::clipboard();
        clipboard->setText(clipboardText);
        qDebug()<<__FUNCTION__<<__LINE__<<clipboardText;
    }
};
#endif // CUSTOMTABLEWIDGET_H
